package com.xike.microgatewayserver.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    /**
     * 执行全局过滤器的业务逻辑
     * @param exchange 请求/响应的上下文对象
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("登录过滤器执行了！！！！");
        log.info("目前GateWay收到的请求路径是：{}",exchange.getRequest().getPath());
//        return chain.filter(exchange);
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getPath().toString();
        //判断是否是swagger的请求
        if (request.getURI().getPath().contains("/v2/api-docs")) {
            //放行
            String substring = path.substring(path.indexOf("/", 1));
            ServerHttpRequest newRequest = request.mutate().path(substring).build();
            log.info("目前swagger收到的请求路径是：{}",substring);
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
            return chain.filter(newExchange);
//            return chain.filter(exchange);
        }
        return chain.filter(exchange);
//        //排除登录请求和注册请求  /sys/login  /sys/register
//        if(        path.equals("/member/login")
//                || path.equals("/member/hostandport")
//                || path.equals("/member/register")
//                || path.equals("/member/createcode")
//                || path.equals("/member/loginbytel")
//                || path.equals("/admin/acl/index/info")
//                || path.equals("/admin/acl/index/menu")
//                || path.equals("/admin/acl/login")
//                || path.equals("/admin/acl/register")
//        ){
//            log.info("过滤器直接放行！！！！");
//            return chain.filter(exchange);
//        }
//        else{
//            //得到authentication信息
//            String authentication = request.getHeaders().getFirst("authentication");
//            if(!StringUtils.hasLength(authentication)){
//                //HttpStatus.UNAUTHORIZED 401 未认证
//                response.setStatusCode(HttpStatus.UNAUTHORIZED);
//                String res = JSONObject.toJSONString(ResultMsg.builder().code(401).msg("认证失败，请先登录！").build());
//                return authError(response,res);
//            }else{
//                //开始JWT令牌认证
//                try{
//                    DecodedJWT verify = JWTUtil.verify(authentication);
//                    Map<String, Object> claims = new HashMap<>();
//                    String memberName = verify.getClaim("memberName").as(String.class);
////                    String telphone = verify.getClaim("telphone").as(String.class);
//                    claims.put("memberName",memberName);
////                    claims.put("telphone",telphone);
//                    String newToken = JWTUtil.createToken(claims);
//                    response.getHeaders().set("authentication",newToken);
//                    //给前端代码，暴露：refreshToken HTTP头
//                    response.getHeaders().set("Access-Control-Expose-Headers","authentication");
//                    //认证通过
//                    return chain.filter(exchange);
//                }catch (Exception e){
//                    response.setStatusCode(HttpStatus.FORBIDDEN);
//                    //令牌的算法错误
//                    if(e instanceof AlgorithmMismatchException){
//                        String res = JSONObject.toJSONString(ResultMsg.builder().code(403).msg("非法令牌，无法识别！").build());
//                        return authError(response,res);
//                        //令牌已失效
//                    }else if(e instanceof TokenExpiredException){
//                        String res = JSONObject.toJSONString(ResultMsg.builder().code(402).msg("令牌已过期，请重新登录！").build());
//                        return authError(response,res);
//                        //签名错误
//                    }else if(e instanceof SignatureVerificationException){
//                        String res = JSONObject.toJSONString(ResultMsg.builder().code(403).msg("非法令牌，无法识别！").build());
//                        return authError(response,res);
//                    }else{
//                        String res = JSONObject.toJSONString(ResultMsg.builder().code(403).msg("非法令牌，未知错误！").build());
//                        return authError(response,res);
//                    }
//                }
//            }
//        }


    }
    /**
     * 认证错误返回
     * @param resp 响应对象
     * @param res  响应的信息
     * @return
     */
    private Mono<Void> authError(ServerHttpResponse resp, String res){
        resp.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        DataBuffer buffer = resp.bufferFactory().wrap(res.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }
    /**
     * 定义过滤器执行顺序
     * 值越小，越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
